package com.wpf.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

//@Slf4j
//@WebServlet(asyncSupported = true,urlPatterns = "aaaasyncServlet")
public class AsyncServlet extends HttpServlet {


    public AsyncServlet() {
       log("异步Servelt");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        // 开始异步操作
        AsyncContext asyncContext = req.startAsync();
        CompletableFuture.runAsync(()->doWork(asyncContext,asyncContext.getRequest(),asyncContext.getResponse()));
        long end = System.currentTimeMillis();
        log("异步总共消耗"+ (end-start) + "秒");
    }

    private void doWork(AsyncContext asyncContext, ServletRequest request, ServletResponse response) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {

        }
        try {
            response.getWriter().append("aSyn done");
        } catch (Exception e) {
            e.printStackTrace();
        }

        asyncContext.complete();//通知结束
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
